public class Main {
    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.isAnagram("anagram", "nagaram"));
        System.out.println(s.isAnagram("rat", "cat"));
    }
}

class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length() != t.length()){
            return false;
        }
        int[] counts = new int[26];
        int countNonZero = 0;
        for(int i = 0; i < s.length(); i++){
            int idxS = s.charAt(i) - 'a';
            int idxT = t.charAt(i) - 'a';
            if(counts[idxS] == 0){
                countNonZero++;
            }
            if(counts[idxS] == -1) {
                countNonZero--;
            }
            counts[idxS]++;

            if(counts[idxT] == 0){
                countNonZero++;
            }
            if(counts[idxT] == 1) {
                countNonZero--;
            }
            counts[idxT]--;
        }
        return countNonZero == 0;
    }
}